package com.example.njut;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

public class CompassActivity extends AppCompatActivity {

    ImageView imageView;
    SensorManager sm;
    SensorListener listener = new SensorListener();
    TextView show;

    static public String localCity;
    //定位
    LocationManager lm;
    TextView locationInfo;

    private static String[] PERMISSIONS_STORGE = {
             Manifest.permission.ACCESS_COARSE_LOCATION,
             Manifest.permission.ACCESS_FINE_LOCATION
     };
     //权限的请求编码
     private static int REQUEST_PERMISSION_CODE = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compass);

       /* if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
            if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!=
                    PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,PERMISSIONS_STORGE,REQUEST_PERMISSION_CODE);
            }
        }*/

        imageView = (ImageView) findViewById(R.id.imageView5);
        show = (TextView) findViewById(R.id.textView26);
        //设置屏幕常亮
        imageView.setKeepScreenOn(true);
        //获得传感器对象
        sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME);

        locationInfo = (TextView) findViewById(R.id.textView27);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!isGpsAble(lm)) {
            Toast.makeText(CompassActivity.this, "请先打开位置信息！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 0);
            CompassActivity.this.finish();
        }
        //通过GPS获取最近一次的位置信息
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location lc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(lc==null){
            lc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        getAddress(lc);
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 10, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                //当定位信息已经发生改变
                getAddress(location);
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {
                if(ActivityCompat.checkSelfPermission(CompassActivity.this,Manifest.permission.ACCESS_COARSE_LOCATION)!=
                        PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(CompassActivity.this,PERMISSIONS_STORGE,REQUEST_PERMISSION_CODE);
                }
                getAddress(lm.getLastKnownLocation(s));
            }
            //作业
            //指南针可以显示朝向
            @Override
            public void onProviderDisabled(String s) {
                getAddress(null);
            }
        });
    }

    /*protected void onResume(){
        Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        sm.registerListener(listener,sensor,SensorManager.SENSOR_DELAY_GAME);
        super.onResume();
    }*/

    private class SensorListener implements SensorEventListener{
        //定义变量记录之前的角度
        float predegree=0;
        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            float degree = sensorEvent.values[0];
            String d="";
            if(degree>=67 && degree<=111){
                d="东（E）";
            } else if(degree>=158 && degree<=202){
                d="南（S）";
            }else if(degree>=247 && degree<=291){
                d="西（W）";
            }else if((degree>=338 && degree<=359) || (degree>=0 && degree<=21)){
                d="北（N）";
            }else if(degree>=112 && degree<=157){
                d="东南（SE）";
            }else if(degree>=203 && degree<=246){
                d="西南（SW）";
            }else if(degree>=22 && degree<=66){
                d="东北（NE）";
            }else if(degree>=292 && degree<=337){
                d="西北（NW）";
            }
            show.setText("方位："+d+"度数："+(int)degree);
            RotateAnimation an = new RotateAnimation(predegree,-degree, Animation.RELATIVE_TO_SELF,0.5f,
                    Animation.RELATIVE_TO_SELF,0.5f);
            //设置动画持续时间
            an.setDuration(250);
            imageView.startAnimation(an);
            predegree=-degree;
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {

        }
    }

    private boolean isGpsAble(LocationManager lm){
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ?true:false;
    }

    private void getAddress(Location lc){
        if(lc!=null){
            StringBuilder sb = new StringBuilder();
            sb.append("当前位置:\n");
            DecimalFormat df = new DecimalFormat(".00");
            sb.append("经度:"+df.format(lc.getLongitude())+" ");
            sb.append("纬度:"+df.format(lc.getLatitude())+"\n");
            Geocoder ge = new Geocoder(CompassActivity.this);
            List<Address> addList = null;
            try {
                //sb.append("当前城市:"+ge.getFromLocation(lc.getLatitude(),lc.getLongitude(),1).get(0).getFeatureName());
                addList = ge.getFromLocation(lc.getLatitude(),lc.getLongitude(),1);

            } catch (IOException e) {
                e.printStackTrace();
            }
            Address ad = addList.get(0);
            sb.append("省份:"+ad.getAdminArea()+" ");  //省份
            sb.append("城市:"+ad.getLocality()+"\n");  //城市
            sb.append("街道(getFeatureName):"+ad.getFeatureName()+"\n");  //街道
            //sb.append("国家代码:"+ad.getCountryCode()+" ");  //国家代码
           // sb.append("国家名称:"+ad.getCountryName()+"\n");  //国家名称
           // sb.append("啥啊:"+ad.getPostalCode()+"\n");
            sb.append("街道(getAddressLine):"+ad.getAddressLine(2)+"\n");
            localCity = ad.getLocality();
            Toast.makeText(CompassActivity.this, localCity, Toast.LENGTH_SHORT).show();
            locationInfo.setText(sb.toString());
        }else{
            locationInfo.setText("当前位置:暂无信息");
            Toast.makeText(CompassActivity.this, "定位失败", Toast.LENGTH_SHORT).show();
        }
    }
}
